package com.admin.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.admin.entity.adminList;

public class FileUtils {
    public static void writeObject(String fileName, Map<String, adminList> map) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
            for (adminList admin : map.values()) {
                // 将 admin 对象的属性按逗号分隔组成一行数据i
                String line = admin.getid() + "," + admin.getPassword() + "," + admin.getUserName();
                bw.write(line);
                bw.newLine();
            }
            System.out.println("写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, adminList> readObject(String fileName) {
        File file = new File(fileName);
        Map<String, adminList> userMap = new HashMap<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            if (!file.exists()) {
                // 文件不存在则直接返回空 Map
                return userMap;
            }
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分割每行数据
                String[] parts = line.split(",");
                String id = parts[0].trim();
                String password = parts[1].trim();
                String userName = parts[2].trim();
                // 创建 adminList 对象
                adminList admin = new adminList(id, password, userName);
                // 将 admin 对象添加到 Map 中
                userMap.put(id, admin);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userMap;
    }
}
